import { eventHandler, getMethod, createError } from "h3";

// 模拟商品数据存储 (实际项目中这应该是共享的数据层)
const products = [
  {
    id: 1,
    name: "iPhone 15",
    price: 7999,
    description: "最新款苹果手机",
    category: "电子产品",
    stock: 50,
    createTime: new Date("2024-01-01").toISOString(),
  },
  {
    id: 2,
    name: "MacBook Pro",
    price: 15999,
    description: "高性能笔记本电脑",
    category: "电子产品",
    stock: 30,
    createTime: new Date("2024-01-02").toISOString(),
  },
  {
    id: 3,
    name: "Nike运动鞋",
    price: 899,
    description: "舒适透气运动鞋",
    category: "服饰",
    stock: 100,
    createTime: new Date("2024-01-03").toISOString(),
  },
];

export default eventHandler(async (event) => {
  const method = getMethod(event);

  // GET /api/stats - 获取商品统计信息
  if (method === "GET") {
    // 计算统计数据
    const totalProducts = products.length;
    const totalStock = products.reduce(
      (sum, product) => sum + product.stock,
      0
    );
    const totalValue = products.reduce(
      (sum, product) => sum + product.price * product.stock,
      0
    );
    const averagePrice =
      products.length > 0
        ? products.reduce((sum, product) => sum + product.price, 0) /
          products.length
        : 0;

    // 找到价格最高和最低的商品
    const maxPriceProduct = products.reduce(
      (max, product) => (product.price > max.price ? product : max),
      products[0]
    );
    const minPriceProduct = products.reduce(
      (min, product) => (product.price < min.price ? product : min),
      products[0]
    );

    // 按分类分组统计
    const categoryStats = products.reduce((stats, product) => {
      if (!stats[product.category]) {
        stats[product.category] = {
          category: product.category,
          count: 0,
          totalStock: 0,
          totalValue: 0,
        };
      }
      stats[product.category].count++;
      stats[product.category].totalStock += product.stock;
      stats[product.category].totalValue += product.price * product.stock;
      return stats;
    }, {} as Record<string, any>);

    // 库存预警商品 (库存小于20的商品)
    const lowStockProducts = products.filter((product) => product.stock < 20);

    return {
      success: true,
      data: {
        overview: {
          totalProducts,
          totalStock,
          totalValue: Math.round(totalValue * 100) / 100, // 保留两位小数
          averagePrice: Math.round(averagePrice * 100) / 100,
        },
        priceRange: {
          maxPrice: {
            price: maxPriceProduct?.price || 0,
            product: maxPriceProduct?.name || "",
          },
          minPrice: {
            price: minPriceProduct?.price || 0,
            product: minPriceProduct?.name || "",
          },
        },
        categoryStats: Object.values(categoryStats),
        alerts: {
          lowStockCount: lowStockProducts.length,
          lowStockProducts: lowStockProducts.map((p) => ({
            id: p.id,
            name: p.name,
            stock: p.stock,
          })),
        },
      },
      timestamp: new Date().toISOString(),
    };
  }

  // 不支持的HTTP方法
  throw createError({
    statusCode: 405,
    statusMessage: "Method Not Allowed",
  });
});
